package com.sgb.kjwl.viewmodel.manage;

import android.content.Context;

import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.BuildConfig;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.lease.LeaseOrderListEntity;
import com.sgb.kjwl.model.entity.transport.PayInfoEntity;
import com.sgb.kjwl.model.entity.transport.TransportOrderEntity;
import com.sgb.kjwl.model.entity.transport.order.MyOrderEntity;
import com.sgb.kjwl.model.entity.user.OrderListEntity;
import com.sgb.kjwl.model.response.ListResponse2;
import com.swgk.core.util.UserOperating;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */
public class AgentTotalOrderModel extends BaseViewModel {
    public ObservableField<Integer> orderType = new ObservableField<>();
    public ObservableField<Map> map = new ObservableField<>(new HashMap());
    private int page = 1;
    private int size = 10;

    //商品列表数据
    private MutableLiveData<List<OrderListEntity>> goodOrderList = new MutableLiveData<>();

    //商品是否展示
    private MutableLiveData<String> showBlankView = new MutableLiveData<>();

    //租赁列表是否加载失败--刷新 还是加载更多
    private MutableLiveData<Boolean> leaseLoadFailed = new MutableLiveData<>();

    //租赁订单列表
    private MutableLiveData<List<LeaseOrderListEntity>> leaseOrderList = new MutableLiveData<>();

    //物流
    public MutableLiveData<PayInfoEntity> ldTradeNo = new MutableLiveData<>();
    //确认订单
    private MutableLiveData<MyOrderEntity> transOrderEntity = new MutableLiveData<>();
    //物流运输订单列表
    private MutableLiveData<List<MyOrderEntity>> transOrderList = new MutableLiveData<>();

    public MutableLiveData<List<OrderListEntity>> getGoodOrderList() {
        return goodOrderList;
    }

    public void setGoodOrderList(MutableLiveData<List<OrderListEntity>> goodOrderList) {
        this.goodOrderList = goodOrderList;
    }

    public MutableLiveData<String> getShowBlankView() {
        return showBlankView;
    }

    public void setShowBlankView(MutableLiveData<String> showBlankView) {
        this.showBlankView = showBlankView;
    }

    public ObservableField<Integer> getOrderType() {
        return orderType;
    }

    public void setOrderType(ObservableField<Integer> orderType) {
        this.orderType = orderType;
    }

    public MutableLiveData<Boolean> getLeaseLoadFailed() {
        return leaseLoadFailed;
    }

    public void setLeaseLoadFailed(MutableLiveData<Boolean> leaseLoadFailed) {
        this.leaseLoadFailed = leaseLoadFailed;
    }

    public MutableLiveData<List<LeaseOrderListEntity>> getLeaseOrderList() {
        return leaseOrderList;
    }

    public void setLeaseOrderList(MutableLiveData<List<LeaseOrderListEntity>> leaseOrderList) {
        this.leaseOrderList = leaseOrderList;
    }

    public MutableLiveData<MyOrderEntity> getTransOrderEntity() {
        return transOrderEntity;
    }

    public void setTransOrderEntity(MutableLiveData<MyOrderEntity> transOrderEntity) {
        this.transOrderEntity = transOrderEntity;
    }

    public MutableLiveData<List<MyOrderEntity>> getTransOrderList() {
        return transOrderList;
    }

    public void setTransOrderList(MutableLiveData<List<MyOrderEntity>> transOrderList) {
        this.transOrderList = transOrderList;
    }

    /**
     * 2019-9-12 11:07:19 新增订单类型待确认：
     *
     * @param isLoadMore
     */
    public void getOrderListModel(Context context, String type, String[] orderState, String orderProcessState, boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        Map<String, Object> map = new HashMap<>(5);
        map.put("page", page);
        map.put("limit", size);
        map.put("type", type);
        map.put("orderState", orderState);
        map.put("orderProcessState", orderProcessState);
        getOrderListModel(context, map);
    }

    /**
     * 采购订单列表请求
     */
    private void getOrderListModel(Context context, Map map) {
        APIManager.getInstance().changeAPIManager(BuildConfig.BASE_URL);
        DialogHelper.showProgressDialog(context, "请求中", 0, false);
        NewAPIManager.getInstance().getShoppingCarNewOrderAPI().getOrdersSimpleList(map).enqueue(new Callback<BaseEntity<ListResponse<List<OrderListEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<OrderListEntity>>>> call, Response<BaseEntity<ListResponse<List<OrderListEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    showBlankView.postValue("");
                    return;
                }
                if (!response.body().getState().equals(AppConstant.REQEUST_SECCUESS)) {
                    showBlankView.postValue(response.body().getMsg());
                    //MToast.showToast(fragment.getActivity(), response.body().getMsg());
                    return;
                }
                goodOrderList.postValue(response.body().getData().getList());
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<OrderListEntity>>>> call, Throwable t) {
                showBlankView.postValue("");
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    //获取租赁-订单列表--个人中心
    public void getLeaseOrderList(Context context, boolean isLoadMore) {
        page = isLoadMore ? page + 1 : 1;
        map.get().put("pageNum", page);
        map.get().put("pageSize", size);
        map.get().put("module", "");//模块  1机械 2设备 3车辆 4房产 5土地 6工厂 7农机
        DialogHelper.showProgressDialog(context, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getLeaseAPI().getOrderList(map.get())
                .enqueue(new Callback<BaseEntity<ListResponse<List<LeaseOrderListEntity>>>>() {
                    @Override
                    public void onResponse(Call<BaseEntity<ListResponse<List<LeaseOrderListEntity>>>> call, Response<BaseEntity<ListResponse<List<LeaseOrderListEntity>>>> response) {
                        DialogHelper.dismissProgressDialog();
                        if (response.body() == null) return;
                        if (APIManager.RESPONSE_OK.equals(response.body().getState())) {
                            leaseOrderList.postValue(response.body().getData().getList());
                        } else {
                            assert response.body() != null;
                            //MToast.showToast(fragment.getActivity(), response.body().getMsg());
                            leaseLoadFailed.postValue(isLoadMore);
                        }
                    }

                    @Override
                    public void onFailure(Call<BaseEntity<ListResponse<List<LeaseOrderListEntity>>>> call, Throwable t) {
                        DialogHelper.dismissProgressDialog();
                        leaseLoadFailed.postValue(isLoadMore);
                    }
                });
    }

    /**
     * app跳转到H5
     *
     * @param id
     * @param type
     */
    public void getH5Url(Context context, String id, String type,String orderType) {
        String name = "";
        if("1".equals(orderType)){//机械
            if ("1".equals(type)) {
                name = "receivedOrder";//求租订单详情
            } else {
                name = "leaseOrder";//出租订单详情
            }
        }else if("2".equals(orderType)){//设备
            if ("1".equals(type)) {
                name = "receivedOrderFacility";//求租订单详情
            } else {
                name = "equipmentRentOutOrderDetails";//出租订单详情
            }
        }
        DialogHelper.showProgressDialog(context, null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(name).enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    String url = response.body().getData().getUrl() + "?id=" + id;
                    WebViewX5HostActivity.start(context, url);
                } else {
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 个人中心专用 货运订单- 分页
     *
     * @param context
     * @param isLodMore
     * @param
     */
    public void getTransList(Context context, boolean isLodMore,int isGoodsOwner) {
        Map map = new HashMap();
        page = isLodMore ? page + 1 : 1;
        //limit
        map.put("limit", 10);
        //page
        map.put("page", page);
        if (UserOperating.getInstance().isCompany()){
            map.put("companyNo",UserOperating.getInstance().getTeamOrCompanyNameNo());
        }else if (UserOperating.getInstance().isTeam()){
            map.put("teamNo",UserOperating.getInstance().getTeamOrCompanyNameNo());
        }else {
            map.put("terminal",3);
        }
       map.put("isGoodsOwner",isGoodsOwner);
        DialogHelper.showProgressDialog(context, "请求中...");

        NewAPIManager.getInstance().getLogisticsAPI().getPendingOrder(map).enqueue(new Callback<BaseEntity<ListResponse2<List<MyOrderEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse2<List<MyOrderEntity>>>> call, Response<BaseEntity<ListResponse2<List<MyOrderEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getData() == null) {
                    transOrderList.postValue(new ArrayList<>());
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    transOrderList.postValue(response.body().getData().getList());
                    if (isGoodsOwner==1){
                        EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_ORDER_OWNER_TOTAL_LIST).setMessageData(response.body().getData().getTotal()));
                    }else {
                        EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_ORDER_DRIVER_TOTAL_LIST).setMessageData(response.body().getData().getTotal()));
                    }

                } else {
                    transOrderList.postValue(new ArrayList<>());
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse2<List<MyOrderEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                transOrderList.postValue(new ArrayList<>());
            }
        });
       /* String url = BuildConfig.NEW_BASE_URL + "logistics/operate/order/freightOrder";
        APIManager.getInstance().getDriverAPI().getTransOwnerOrder(url, 10, page).enqueue(new Callback<BaseEntity<ListResponse<List<MyOrderEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<MyOrderEntity>>>> call, Response<BaseEntity<ListResponse<List<MyOrderEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getData() == null) {
                    transOrderList.postValue(new ArrayList<>());
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    transOrderList.postValue(response.body().getData().getList());
                } else {
                    transOrderList.postValue(new ArrayList<>());
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<MyOrderEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                transOrderList.postValue(new ArrayList<>());
            }
        });*/
    }

    /**
     * 确认订单
     *
     * @param context
     */
    public void getSureOrder(Context context, MyOrderEntity item) {
        Map map = new HashMap();
        map.put("orderNo", item.getOrderNo());
        DialogHelper.showProgressDialog(context, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().sureOrder(map).enqueue(new Callback<BaseEntity<TransportOrderEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<TransportOrderEntity>> call, Response<BaseEntity<TransportOrderEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok")) {
                    transOrderEntity.postValue(item);
                } else {
                    MToast.showToast(context, response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<TransportOrderEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 支付运费
     *
     * @param activity
     * @param orderNo
     */
    public void getPayFreight(Context activity, String orderNo) {
        Map map = new HashMap();
        map.put("orderNo", orderNo);
        DialogHelper.showProgressDialog(activity, null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().payFreight(map).enqueue(new Callback<BaseEntity<PayInfoEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<PayInfoEntity>> call, Response<BaseEntity<PayInfoEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData() == null)
                    return;

                if (response.body().getState().equals("ok") && response.body().getData().getResult().equals("200")) {
                    ldTradeNo.postValue(response.body().getData());
                } else {
                    MToast.showToast(activity, response.body().getData().getMessage());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<PayInfoEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
